<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*, javax.servlet.*, java.net.*"
	import="javax.servlet.http.*" 
	import="org.apache.commons.fileupload.*"
	import="org.apache.commons.fileupload.disk.*"
	import="org.apache.commons.fileupload.servlet.*"
	import="org.apache.commons.io.output.*"
	import="org.json.simple.JSONObject"
	import="org.json.simple.parser.JSONParser"
	import="org.apache.commons.codec.binary.Base64"
	import="com.netcracker.studportal.server.facade.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
	int maxFileSize = 10000 * 1024;
	int maxMemSize = 10000 * 1024;

	// Verify the content type
	String contentType = request.getContentType();
	if (contentType != null
			&& (contentType.indexOf("multipart/form-data") >= 0)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// maximum size that will be stored in memory
		factory.setSizeThreshold(maxMemSize);
		// Location to save data that is larger than maxMemSize.
		factory.setRepository(new File("C:\\temp"));

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);
		// maximum file size to be uploaded.
		upload.setSizeMax(maxFileSize);
		try {
			String examID = null, materialName = null, returnURL = null;
			// Parse the request to get file items.
			List<FileItem> fileItems = upload.parseRequest(request);
			for (FileItem fi : fileItems) {
				if (fi.isFormField()) {
					String fieldName = fi.getFieldName();
					String fieldValue = new String(fi.get(), "UTF-8");
		
					if ("exam_id".equals(fieldName)) {
						examID = fieldValue;
					} else if ("material_name".equals(fieldName)) {
						materialName = fieldValue;
					} else if ("return".equals(fieldName)) {
						returnURL = fieldValue;
					}
				}
			}

			// Process the uploaded file items
			Iterator<FileItem> i = fileItems.iterator();

			out.println("<html>");
			out.println("<head>");
			out.println("<title>Upload File Page</title>");
			out.println("</head>");
			out.println("<body>");
			while (i.hasNext()) {
				FileItem fi = i.next();
				if (!fi.isFormField()) {
					// Get the uploaded file parameters
					String fieldName = fi.getFieldName();
					String fileName = fi.getName();
					boolean isInMemory = fi.isInMemory();
					long sizeInBytes = fi.getSize();

					//out.println("Uploaded Filename: " + fi.getName() + "<br>");
				}
				
				FacadeProfessor facadeProfessor = new FacadeProfessor();

				JSONObject inputParams = new JSONObject();

				String fileName = fi.getName();
				fileName = URLEncoder.encode(fileName);
				inputParams.put("file_name", fileName);

				byte[] byteArray = fi.get();
				String fileContent = Base64.encodeBase64URLSafeString(byteArray);
				inputParams.put("file_content", fileContent);

				inputParams.put("exam_id", examID);
				if (materialName == null || materialName.isEmpty()) {
					materialName = fileName;
				}
				inputParams.put("material_name", materialName);

				String result = facadeProfessor.addMaterialByExam(inputParams.toJSONString());
				JSONObject jsonRes = (JSONObject) new JSONParser().parse(result);
				if ("success".equals(jsonRes.get("status"))) {
					response.sendRedirect(returnURL);
				} else {
					out.print("Ошибка: " + jsonRes.get("error"));
				}
			}
			out.println("</body>");
			out.println("</html>");
		} catch (Exception ex) {
			System.out.println(ex);
		}
	} else {
		out.println("<html>");
		out.println("<head>");
		out.println("<title>Upload File Page</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<p>Нет файла для загрузки</p>");
		out.println("</body>");
		out.println("</html>");
	}
%>